/*
 * 文件名：LoginInterceptor.java
 * 版权：Copyright by 联通系统集成有限公司
 * 描述：
 * 修改人：焦凯旋
 * 修改时间：2019年6月21日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.bicycle.wxpublic.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.CommonBusinessCodeEnum;
import com.bicycle.common.helper.SignatureHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SignInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Environment environment;

    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        // api 验证开关
        int apiValidateSwitch = StringUtils.isNoneBlank(environment.getProperty("api.validate.switch")) ? Integer.parseInt(environment.getProperty("api.validate.switch")) : 1;
        if (apiValidateSwitch == 1) {
            // 校验签名
            Map<String, Object> parameters = new HashMap<String, Object>();
            if (StringUtils.equalsIgnoreCase(request.getMethod(), "GET")) {
                // GET方法
                Map<String, String[]> map = request.getParameterMap();
                for (String key : map.keySet()) {
                    parameters.put(key, map.get(key)[0]);
                }
            } else if (StringUtils.equalsIgnoreCase(request.getMethod(), "POST")) {
                // POST方法
                if (StringUtils.contains(request.getContentType(), "application/json")) {
                    StringBuffer buffer = new StringBuffer();
                    InputStream inputStream = request.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.append(line + "\n");
                    }
                    // json格式
                    log.info(">>>>>>获取json数据:{}", buffer.toString());
                    JSONObject jsonObject = JSON.parseObject(buffer.toString());
                    for (String key : jsonObject.keySet()) {
                        parameters.put(key, jsonObject.getString(key));
                    }
                } else {
                    Map<String, String[]> map = request.getParameterMap();
                    for (String key : map.keySet()) {
                        parameters.put(key, map.get(key)[0]);
                    }
                }
            }
            if (!SignatureHelper.isSignatureValid(parameters, environment.getProperty("api.secret"))) {
                Message message = new Message();
                message.setCode(CommonBusinessCodeEnum.CODE_SIGN_ERROR.getKey());
                message.setMessage(CommonBusinessCodeEnum.CODE_SIGN_ERROR.getValue());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSON.toJSONString(message));
                return false;
            }
        }
        return true;
    }
}
